/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 音频服务处理器 - 实现锁屏界面音频控制功能
 * 
 * 功能特性：
 * 1. 锁屏界面音频信息显示（歌曲名称、歌手、专辑封面等）
 * 2. 锁屏界面播放控制按钮（播放/暂停、上一首、下一首）
 * 3. 兼容不同手机厂商的锁屏界面实现
 * 4. 实时同步音频信息更新
 */

import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:flutter/foundation.dart';

import '../viewmodels/music_player_view_model.dart';
import '../models/music_item_model.dart';

/// 音频服务处理器
/// 负责管理锁屏界面的音频信息显示和控制功能
class AudioServiceHandler extends BaseAudioHandler
    with QueueHandler, SeekHandler {
  /// 单例模式
  static AudioServiceHandler? _instance;
  static AudioServiceHandler get instance {
    _instance ??= AudioServiceHandler._internal();
    return _instance!;
  }

  AudioServiceHandler._internal();

  /// 音乐播放器视图模型
  MusicPlayerViewModel? _musicPlayerViewModel;

  /// 是否已设置监听器
  bool _listenersSetup = false;

  /// 是否已初始化
  bool _isInitialized = false;

  /// 初始化音频服务
  /// [musicPlayerViewModel] 音乐播放器视图模型实例
  Future<void> initialize(MusicPlayerViewModel musicPlayerViewModel) async {
    if (_isInitialized) return;

    _musicPlayerViewModel = musicPlayerViewModel;

    try {
      // 初始化音频服务
      await AudioService.init(
        builder: () => this,
        config: const AudioServiceConfig(
          androidNotificationChannelId: 'com.hzy.music.channel.audio',
          androidNotificationChannelName: '音乐播放',
          androidNotificationOngoing: false,
          androidShowNotificationBadge: true,
          androidNotificationChannelDescription: '音乐播放控制',
          androidNotificationIcon: 'drawable/ic_launcher',
          androidStopForegroundOnPause: false,
        ),
      );

      // 设置初始播放状态
      playbackState.add(PlaybackState(
        controls: [
          MediaControl.skipToPrevious,
          MediaControl.play,
          MediaControl.skipToNext,
        ],
        systemActions: const {
          MediaAction.seek,
          MediaAction.seekForward,
          MediaAction.seekBackward,
        },
        androidCompactActionIndices: const [0, 1, 2],
        processingState: AudioProcessingState.idle,
        playing: false,
        updatePosition: Duration.zero,
        bufferedPosition: Duration.zero,
        speed: 1.0,
      ));

      // 监听播放器状态变化
      _setupPlayerListeners();

      _isInitialized = true;
      debugPrint('AudioServiceHandler: 初始化完成');
    } catch (error, stackTrace) {
      debugPrint('AudioServiceHandler初始化失败: $error');
      debugPrint('StackTrace: $stackTrace');
    }
  }

  /// 设置播放器监听器
  void _setupPlayerListeners() {
    if (_musicPlayerViewModel == null || _listenersSetup) return;

    // 监听播放状态变化
    _musicPlayerViewModel!.isPlaying.addListener(_updatePlaybackState);

    // 监听播放位置变化
    _musicPlayerViewModel!.position.addListener(_updatePosition);

    // 监听播放时长变化
    _musicPlayerViewModel!.duration.addListener(_updatePosition);

    // 监听当前播放音乐变化
    _musicPlayerViewModel!.addListener(_onViewModelChanged);

    _listenersSetup = true;
  }

  /// 视图模型变化回调
  void _onViewModelChanged() {
    final currentTrack = _musicPlayerViewModel?.currentTrack;
    if (currentTrack != null) {
      _updateMediaItem(currentTrack);
    }
    _updatePlaybackState();
  }

  /// 更新媒体项信息
  /// [music] 当前播放的音乐信息
  void _updateMediaItem(MusicItemModel music) {
    try {
      final mediaItem = MediaItem(
        id: music.id,
        album: music.album.isNotEmpty ? music.album : '未知专辑',
        title: music.title.isNotEmpty ? music.title : '未知歌曲',
        artist: music.artist.isNotEmpty ? music.artist : '未知歌手',
        duration: _musicPlayerViewModel?.duration.value ?? Duration.zero,
        artUri: music.albumArt?.isNotEmpty == true
            ? Uri.parse(music.albumArt!)
            : null,
        extras: {
          'audioUrl': music.audioUrl,
          'sourceType': music.sourceType,
        },
      );

      this.mediaItem.add(mediaItem);
      debugPrint('AudioServiceHandler: 媒体项已更新 - ${music.title}');
    } catch (error) {
      debugPrint('AudioServiceHandler: 更新媒体项失败 - $error');
    }
  }

  /// 更新播放状态
  void _updatePlaybackState() {
    try {
      final isPlaying = _musicPlayerViewModel?.isPlaying.value ?? false;
      final position = _musicPlayerViewModel?.position.value ?? Duration.zero;
      final duration = _musicPlayerViewModel?.duration.value ?? Duration.zero;
      final isLoading = _musicPlayerViewModel?.isLoading ?? false;

      final processingState = isLoading
          ? AudioProcessingState.loading
          : isPlaying
              ? AudioProcessingState.ready
              : AudioProcessingState.ready;

      playbackState.add(PlaybackState(
        controls: [
          MediaControl.skipToPrevious,
          isPlaying ? MediaControl.pause : MediaControl.play,
          MediaControl.skipToNext,
        ],
        systemActions: const {
          MediaAction.seek,
          MediaAction.seekForward,
          MediaAction.seekBackward,
        },
        androidCompactActionIndices: const [0, 1, 2],
        processingState: processingState,
        playing: isPlaying,
        updatePosition: position,
        bufferedPosition: duration,
        speed: 1.0,
      ));

      debugPrint(
          'AudioServiceHandler: 播放状态已更新 - playing: $isPlaying, position: ${position.inSeconds}s');
    } catch (error) {
      debugPrint('AudioServiceHandler: 更新播放状态失败 - $error');
    }
  }

  /// 更新播放位置
  void _updatePosition() {
    try {
      final currentState = playbackState.value;
      final position = _musicPlayerViewModel?.position.value ?? Duration.zero;
      final duration = _musicPlayerViewModel?.duration.value ?? Duration.zero;

      playbackState.add(currentState.copyWith(
        updatePosition: position,
        bufferedPosition: duration,
      ));
    } catch (error) {
      debugPrint('AudioServiceHandler: 更新播放位置失败 - $error');
    }
  }

  // ========== 媒体控制接口实现 ========== //

  /// 播放
  @override
  Future<void> play() async {
    try {
      if (_musicPlayerViewModel?.hasCurrentTrack == true) {
        await _musicPlayerViewModel?.resume();
      } else if (_musicPlayerViewModel?.hasPlaylist == true) {
        await _musicPlayerViewModel?.playAtIndex(0);
      }
      debugPrint('AudioService: 播放');
    } catch (error) {
      debugPrint('AudioService播放失败: $error');
    }
  }

  /// 暂停
  @override
  Future<void> pause() async {
    try {
      await _musicPlayerViewModel?.pause();
      debugPrint('AudioService: 暂停');
    } catch (error) {
      debugPrint('AudioService暂停失败: $error');
    }
  }

  /// 停止
  @override
  Future<void> stop() async {
    try {
      await _musicPlayerViewModel?.stop();
      debugPrint('AudioService: 停止');
    } catch (error) {
      debugPrint('AudioService停止失败: $error');
    }
  }

  /// 跳转到上一首
  @override
  Future<void> skipToPrevious() async {
    try {
      await _musicPlayerViewModel?.previous();
      debugPrint('AudioService: 上一首');
    } catch (error) {
      debugPrint('AudioService上一首失败: $error');
    }
  }

  /// 跳转到下一首
  @override
  Future<void> skipToNext() async {
    try {
      await _musicPlayerViewModel?.next();
      debugPrint('AudioService: 下一首');
    } catch (error) {
      debugPrint('AudioService下一首失败: $error');
    }
  }

  /// 跳转到指定位置
  /// [position] 目标位置
  @override
  Future<void> seek(Duration position) async {
    try {
      await _musicPlayerViewModel?.seekTo(position);
      debugPrint('AudioService: 跳转到 ${position.inSeconds}秒');
    } catch (error) {
      debugPrint('AudioService跳转失败: $error');
    }
  }

  /// 设置播放速度
  /// [speed] 播放速度
  @override
  Future<void> setSpeed(double speed) async {
    try {
      // audioplayers 插件暂不支持播放速度设置
      debugPrint('AudioService: 设置播放速度 ${speed}x (暂不支持)');
    } catch (error) {
      debugPrint('AudioService设置播放速度失败: $error');
    }
  }

  /// 手动更新锁屏信息
  /// 用于在特定情况下强制同步音频信息
  void updateLockscreenInfo() {
    final currentTrack = _musicPlayerViewModel?.currentTrack;
    if (currentTrack != null) {
      _updateMediaItem(currentTrack);
    }
    _updatePlaybackState();
    debugPrint('AudioServiceHandler: 手动更新锁屏信息');
  }

  /// 释放资源
  Future<void> dispose() async {
    if (!_isInitialized) return;

    try {
      // 移除监听器
      if (_listenersSetup && _musicPlayerViewModel != null) {
        _musicPlayerViewModel!.isPlaying.removeListener(_updatePlaybackState);
        _musicPlayerViewModel!.position.removeListener(_updatePosition);
        _musicPlayerViewModel!.duration.removeListener(_updatePosition);
        _musicPlayerViewModel!.removeListener(_onViewModelChanged);
      }

      _musicPlayerViewModel = null;
      _isInitialized = false;
      _listenersSetup = false;

      debugPrint('AudioServiceHandler: 资源已释放');
    } catch (error) {
      debugPrint('AudioServiceHandler释放资源失败: $error');
    }
  }
}
